import tkinter as tk
import tkinter.ttk as ttk
import socket,threading
s1=socket.socket()
shut=0
gbb=1
hostname=socket.gethostname()
hostip=socket.gethostbyname(f'{hostname}')
duankou=666
def shou(new_s, socket_list):  # 创建一个收的函数
    global ne,text
    try:
        nikename = new_s.recv(1024).decode('utf-8').strip()  # 为当前客户端执行一次‘收'来获取
    except:
        new_s.close()  # 关闭当前客户端的套接字
        socket_list.remove(new_s)  # 去除套接字列表里的nes_s
        for i in socket_list:
            i.send('\n公告:一个未知的人离开了聊天室......'.encode('utf-8'))  # 广播
        return None
    for i in socket_list:
        i.send(f'\n公告:欢迎{nikename}进入了聊天室........\n-------------------\n'.encode('utf-8'))  # 广播
    text.insert(tk.END,f'\n{nikename}进入了聊天室开始聊天\n-------------------\n')
    while 1:
        try:
            recv_data = new_s.recv(1024).decode('utf-8')  # 如果接受到了客户端发来的信息
            print(recv_data)  # 仅作提醒用
            for i in socket_list:
                i.send(f'{nikename}:{recv_data}'.encode('utf-8'))  # 广播
            text.insert(tk.END,f'{nikename}:{recv_data}')
        except:
            new_s.close()  # 关闭当前客户端的套接字
            socket_list.remove(new_s)  # 去除套接字列表里的nes_s
            for i in socket_list:
                i.send(f'公告:{nikename}离开了聊天室......'.encode('utf-8'))  # 广播
            break  # 跳出循环
def gbbk():
    global gbb,la2
    gbb=2
    la2.config(text='成功建立连接...等待接入....')
def fa(new_s):
    print('fa')
    msg = '\n'  # 发出
    new_s.send(msg.encode('utf-8'))
def connt():
    global shut
    adr=en1.get()
    duan=int(en2.get())
    s1.bind((f'{adr}',duan))
    s1.listen(5)
    text.insert(tk.END,'waiting.....\n')
    shut=1
def accept():
    msg=conn.recv(1024)
    print(msg)
    text.insert(0.0,msg)
    text.after(500,accept)
def link():
    global hostip,duankou,en2
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定
    duankou = int(en2.get())
    s.bind((f"{hostip}",duankou))  # 端口
    # 监听
    s.listen(5)
    print('服务端处于监听状态，等待客户端接入..........')
    socket_list = []
    while 1:
        # 接入
        new_s, addr = s.accept()
        print('客户端已接入')
        la2.config(text=f'客户端已接入，来自ip【{addr[0]}】监听中...\n')
        socket_list.append(new_s)
        new_s.send('提示：请先输入昵称'.encode('utf-8'))
        t1 = threading.Thread(target=shou, args=(new_s, socket_list))
        t2 = threading.Thread(target=fa, args=(new_s,))
        t1.start()
        t2.start()
    
def mainwin():
    global la2,en2,text
    root=tk.Tk()
    root.geometry("600x300+400+300")
    root.title('局域网聊天主机端v1.0')
    su=tk.LabelFrame(root,text='聊天设置',font='微软雅黑 10',pady=5)
    su.pack(fill=tk.X,padx=5,pady=5)
    con=tk.Button(su,text='创建连接',padx=5,bg='lightskyblue',command=gbbk)
    con.pack(side=tk.LEFT,pady=2,padx=10)
    la=tk.Label(su,text='       主机IP',font='微软雅黑 10')
    la.pack(side=tk.LEFT,padx=5)

    en1=tk.Entry(su)
    en1.pack(side=tk.LEFT)
    en1.insert(0,f'{hostip}')

    la1=tk.Label(su,text='       端口',font='微软雅黑 10')
    la1.pack(side=tk.LEFT,padx=5)
    en2=tk.Entry(su)
    en2.pack(side=tk.LEFT)
    en2.insert(0,666)

    f1=tk.Frame(root)
    f1.pack(fill=tk.BOTH)

    se=ttk.Separator(root,orient=tk.HORIZONTAL)
    se.pack(fill=tk.X)
    f2=tk.Frame(root)
    f2.pack(fill=tk.BOTH)
    la2=tk.Label(f2,text='目前连接状态：-----',font='微软雅黑 10')
    la2.pack(side=tk.TOP,padx=5)
    se=ttk.Separator(root,orient=tk.HORIZONTAL)
    se.pack(fill=tk.X)
    #------------聊天输入框----------------
    text=tk.Text(root,font='微软雅黑 10',height=9)
    text.pack(fill=tk.X,padx=3,pady=5)
    root.mainloop()
thread1 = threading.Thread(target=mainwin)
thread2 = threading.Thread(target=link)
thread1.start()
while gbb:
    if gbb==2:
        thread2.start()
        gbb=0
